package com.wl.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test01 {
    public static void main(String[] args) throws ClassNotFoundException,
            IllegalAccessException, InstantiationException, NoSuchFieldException {
        Class<?> aClass = Class.forName("com.wl.reflection.User");
        System.out.println("aClass = " + aClass);

        //获取类的属性
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field : declaredFields) {
            System.out.println("field = " + field);
        }

        //获取本类的方法
        Method[] methods = aClass.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println("method = " + method);
        }

        //操作属性
        User user = (User) aClass.newInstance();
        Field name = aClass.getDeclaredField("name");
        //关闭安全检测，操作私有属性
        name.setAccessible(true);
        name.set(user,"王磊");
        System.out.println("name.getName() = " + user.getName());
    }
}

class User {
    private int id;
    private String name;
    private int age;

    public User() {
    }

    public User(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}